package javawdw.security;

import java.util.ArrayList;
import java.util.List;

import javawdw.security.dao.RoleDao;
import javawdw.security.dao.UserDao;
import javawdw.security.entity.Role;
import javawdw.security.entity.User;

import org.springframework.dao.DataAccessException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

public class UserService implements UserDetailsService {
	private UserDao userDao;
	private RoleDao roleDao;

	public User loadUserByUsername(String username)
			throws UsernameNotFoundException, DataAccessException {
		User user = userDao.findFirstByProperty("username", username);
		if (user != null) {
			List<Role> list = roleDao.findByUserId(user.getId());
			List<GrantedAuthority> temp = new ArrayList<GrantedAuthority>();
			for (int i = 0; i < list.size(); i++) {
				temp.add(list.get(i));
			}
			user.setAuthorities(temp);
		} else {
			throw new UsernameNotFoundException(username);
		}
		return user;
	}

	public void setUserDao(UserDao userDao) {
		this.userDao = userDao;
	}

	public void setRoleDao(RoleDao roleDao) {
		this.roleDao = roleDao;
	}
}